//
//  WmcLocalAlbumVM.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/28.
//

import RxRelay
import UIKit
import YPBedrock

// MARK: - [WmcLocalAlbumVM]

class WmcLocalAlbumVM: WmcBaseVM {
    // MARK: 输出
    
    /// 本地图片数据信号量
    let groupLocalMediaRelay: BehaviorRelay<[WmcLocalAlbumGroupModel]> = .init(value: [])

    // MARK: 回调

    /// 刷新媒体列表回调
    var refreshMediaBlock: YPBlock.OneParam<[WmcMedia]>?

    /// 但会媒体列表回调
    var backMediaBlock: YPBlock.TwoParam<[WmcMedia], [WmcLocalMediaAlbumDBManager.DBModel]>?

    // MARK: 其他

    /// 记录媒体数据库原始数据结构
    var mediaList: [WmcMedia] = []
    /// 记录媒体数据库原始数据结构
    var dbModelList: [WmcLocalMediaAlbumDBManager.DBModel] = []

    override func config() {
        pageSize = 200
    }
    
    // MARK: 输入

    /// 刷新数据
    func refreshData() {
        page = 1
        WmcLocalMediaAlbumDBManager.searchMediaData(page: page,pageSize: pageSize) { [weak self] mediaList in
            guard let weakSelf = self else { return }
            
            let list = weakSelf.filterDBModelMediaType(mediaList)
            let groupByList = weakSelf.groupBy(list)
            weakSelf.refreshRelay.accept(.end)

            // 回调数据刷新
            var mediaList: [WmcMedia] = []
            list.forEach { dbModel in
                if let filePath = dbModel.mediaInfoType.filePath {
                    switch dbModel.mediaType {
                    case .image:
                        mediaList.append(WmcImage(filePath: filePath))
                    case .video:
                        mediaList.append(WmcVideo(filePath: filePath))
                    default: break
                    }
                }
            }
            weakSelf.mediaList = mediaList
            weakSelf.dbModelList = list
            weakSelf.outputLocalImage(groupByList)
            weakSelf.refreshMediaBlock?(mediaList)
            
        }
    }
    
    /// 加载更多数据
    func loadMoreData() {
        page += 1
        WmcLocalMediaAlbumDBManager.searchMediaData(page: page,pageSize: pageSize) { [weak self] mediaList in
            guard let weakSelf = self else { return }

            let list = weakSelf.filterDBModelMediaType(mediaList)
            if list.isEmpty {
                weakSelf.refreshRelay.accept(.noMore)
                return
            }
            
            let groupByList = weakSelf.groupBy(list)
            var currentList = weakSelf.groupLocalMediaRelay.value
            let newList = currentList.wmc_appendLocalAlbumGroup(groupByList)
            weakSelf.outputLocalImage(newList)
            if list.count < weakSelf.pageSize {
                weakSelf.refreshRelay.accept(.noMore)
            } else {
                weakSelf.refreshRelay.accept(.end)
            }
        }
    }

    
    func groupBy(_ list: [WmcLocalMediaAlbumDBManager.DBModel]) -> [WmcLocalAlbumGroupModel] {
        // 进行分组
        var dateDic: [String: [WmcLocalMediaAlbumDBManager.DBModel]] = [:]
        list.forEach { imageModel in
            let saveDate = imageModel.saveTime - 8.yp.hour
            let keyDate = saveDate.yp.string(.iso8601Day, identifier: .asia(.Shanghai))
            if var arr = dateDic[keyDate] {
                arr.append(imageModel)
                dateDic[keyDate] = arr
            } else {
                dateDic[keyDate] = [imageModel]
            }
        }
        // 排序
        let sortArr = dateDic.keys.sorted { str, str2 in
            return str.yp.replacing("-", with: "").yp.int > str2.yp.replacing("-", with: "").yp.int
        }
        // 根据排序进行处理数据
        var results: [WmcLocalAlbumGroupModel] = []
        sortArr.forEach { key in
            if let dataList = dateDic[key] {
                let model: WmcLocalAlbumGroupModel = .init(title: key, list: dataList)
                model.count = dataList.count
                results.append(model)
            }
        }
        return results
    }

    func outputLocalImage(_ list: [WmcLocalAlbumGroupModel]) {
        groupLocalMediaRelay.accept(list)
    }

    /// 过滤媒体类型
    func filterDBModelMediaType(_ list: [WmcLocalMediaAlbumDBManager.DBModel]) -> [WmcLocalMediaAlbumDBManager.DBModel] {
        var defaultTypes: [WmcMedia.MediaType] = [.image, .video]
        if let localAlbumDelegate = YPWmcManager.shared.uiDelegate.localAlbumDelegate {
            defaultTypes = localAlbumDelegate.loadMediaType(.current, defaultMediaTypes: defaultTypes)
        }
        var newList: [WmcLocalMediaAlbumDBManager.DBModel] = []
        for media in list {
            if defaultTypes.contains(media.mediaType) { // 包含类型
                newList.append(media)
            }
        }
        return newList
    }

    /// 过滤媒体类型
    func filterMediaType(_ list: [WmcMedia]) -> [WmcMedia] {
        var defaultTypes: [WmcMedia.MediaType] = [.image, .video]
        if let localAlbumDelegate = YPWmcManager.shared.uiDelegate.localAlbumDelegate {
            defaultTypes = localAlbumDelegate.loadMediaType(.current, defaultMediaTypes: defaultTypes)
            var newList: [WmcMedia] = []
            for media in list {
                if defaultTypes.contains(media.mediaType()) { // 包含类型
                    newList.append(media)
                }
            }
            return newList
        }
        return list
    }

    /// 返回的回调
    func backActionCall() {
        let newList = filterMediaType(mediaList)
        backMediaBlock?(newList,dbModelList)
    }
}

fileprivate extension Array where Element == WmcLocalAlbumGroupModel {
    /// 数据拼接
    mutating func wmc_appendLocalAlbumGroup(_ arr: [Element]) -> [Element] {
        guard let lastObj = self.last,
              let firstObj = arr.first else { return self }
        var group = arr
        if lastObj.title == firstObj.title { // 需要合并
            let newTitle = lastObj.title
            let newList = lastObj.list + firstObj.list
            let newCount = lastObj.count
            let newModel: WmcLocalAlbumGroupModel = .init(title: newTitle, list: newList)
            newModel.count = newCount
            // 移除多余的
            self.removeLast()
            group.removeFirst()
            self.append(newModel) // 拼接新的
        }
        self += group
        return self
    }
}
